from rest_framework.serializers import ModelSerializer,SerializerMethodField
from rest_framework import serializers
from community.models import Article, Comment


class ArticleSerializer(ModelSerializer):# 文章序列化器
    class Meta:
        model = Article
        exclude = ['is_delete']

class CommentSerializer(ModelSerializer):# 评论序列化器
    user_name = serializers.CharField(source='user.first_name',read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar',read_only=True)
    reply_name = SerializerMethodField()

    class Meta:
        model = Comment
        fields = '__all__'

    def get_reply_name(self,comment):
        try:
            user =Comment.objects.get(id=comment.reply_comment).user
            reply_name = user.first_name
        except:
            reply_name=None
        return reply_name

class CommentHandlerSerializer(ModelSerializer): # 评论处理
    son_comment =SerializerMethodField() # 存储所有评论id为2的

    class Meta:
        model = Comment
        fields ='__all__'

    def get_son_comment(self,comment):
        # 查询所有parent_comment为level为1的评论的id的评论
        serializer = CommentSerializer(Comment.objects.filter(parent_comment=comment.id),many=True)
        data = serializer.data
        data.reverse()
        return data